package com.ygqh.baby.service.wechat.notify;

import org.apache.log4j.Logger;

import com.ygqh.baby.service.wechat.util.Signature;
import com.ygqh.baby.service.wechat.util.XMLParser;

/**
 * Created by Administrator on 2015/7/29.
 */
public class PayNotifyTemplate {

	protected final Logger logger = Logger.getLogger(this.getClass());

	private PayNotifyData payNotifyData;

	public PayNotifyTemplate(String notifyXml) {
		boolean isValid = Signature.checkIsSignValidFromResponseString(notifyXml);
		if (isValid) {
			payNotifyData = XMLParser.getObjectFromXML(notifyXml, PayNotifyData.class);
		}

	}

	public String execute(PaySuccessCallBack successCallBack) {
		ResponseData responseData = new ResponseData();
		if (payNotifyData == null) {
			responseData.setReturn_code("FAIL");
			responseData.setReturn_msg("签名错误");
			String xml = XMLParser.toXML(responseData);
			logger.warn("微信支付回调验证失败；【无回调信息】" + xml);
			return xml;
		}
		logger.info("receive data from wechat:" + payNotifyData);
		if ("SUCCESS".equals(payNotifyData.getReturn_code()) && "SUCCESS".equals(payNotifyData.getResult_code())) {

			if (successCallBack != null) {
				try {

					successCallBack.onSuccess(payNotifyData);
					responseData.setReturn_code("SUCCESS");
					responseData.setReturn_msg("OK");
				} catch (Exception e) {
					responseData.setReturn_code("FAIL");
					responseData.setReturn_msg(e.getMessage());
				}

			}
		}
		String xml = XMLParser.toXML(responseData);
		logger.info("微信支付回调验证：" + xml);
		return xml;

	}

}
